import { Service } from 'egg';
const { Op } = require('sequelize');

export default class UserRole extends Service {
  // 给用户分配角色
  public async createUserRole(obj) {
    const { userId, roleId } = obj;
    const user = await this.ctx.model.UserRole.findOne({
      where: {
        [Op.and]: [
          { userId },
          { roleId },
        ],
      },
    });
    if (user) {
      throw new Error('用户已经拥有该角色');
    }
    try {
      const data = await this.ctx.model.UserRole.create(obj);
      const userRoleData = data.dataValues;
      return userRoleData;
    } catch (e) {
      // console.log(e);
      throw new Error('分配角色失败');
    }
  }

  // 删除用户角色
  public async destroyUserRole(userId, roleId) {
    const user = await this.ctx.model.UserRole.findOne({
      where: {
        [Op.and]: [
          { userId },
          { roleId },
        ],
      },
    });
    if (user) {
      const data = await this.ctx.model.UserRole.destroy({
        where: {
          userId,
          roleId,
        },
      });
      if (data > 0) {
        return data;
      }
      throw new Error('删除角色失败');
    } else {
      throw new Error('用户没有该角色');
    }
  }
}
